/**
 * FormFieldMarkdown
 * 完整配置详见cherry：https://github.com/Tencent/cherry-markdown/wiki/%E9%85%8D%E7%BD%AE%E9%A1%B9%E5%85%A8%E8%A7%A3
 */
 layui.define(['FormField', 'yunj', 'jquery'], function (exports) {

    let FormField = layui.FormField;
    let win = window;
    let doc = document;
    let $ = layui.jquery;

    class FormFieldMarkdown extends FormField {

        constructor(options = {}) {
            super(options);
            this.mode = null;                   // 模式
            this.markdownContainerId = null;    // 容器id
            this.markdown = null;               // 对象
        }

        defineExtraArgs() {
            return {
                height: 'auto',
                toolbar: [
                    'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'strikethrough', 'color', 'size', '|',
                    'header', 'list', 'hr', 'panel', '|',
                    'image', 'link', 'code', 'table', '|', 'togglePreview',
                ],
                toolbarRight: ['export', 'theme', 'copy'],
                mobileToolbar: [
                    'undo',
                    {bold: ['bold', 'italic', 'underline', 'strikethrough', 'color', 'size']}, 'header',
                    {insert: ['list', 'hr', 'panel', 'image', 'link', 'code', 'table']}, 'togglePreview',
                ],
            };
        }

        layoutControl() {
            let that = this;
            return `<div class="layui-input-inline yunj-form-item-control cherry"><div id="${that.markdownContainerId}" style="width: 100%;height:auto;box-sizing: border-box"></div></div>`;
        }

        async renderBefore() {
            let that = this;
            that.markdownContainerId = `${that.id}_markdown`;
            await yunj.includeCss('/static/yunj/libs/cherry-markdown/dist/cherry-markdown.min.css');
            await yunj.includeJs('/static/yunj/libs/cherry-markdown/dist/cherry-markdown.core.js');
            return 'done';
        }

        async renderDone() {
            let that = this;
            that.setHeight(that.args.height);
            let options = that.getCherryOptions();
            that.markdown = new Cherry(options);
            return 'done';
        }

        async setValue(val = '') {
            let that = this;
            val = val || '';
            that.markdown.setValue(val,true);
        }

        getValue() {
            let that = this;
            return that.markdown.getMarkdown();
        }

        // 设置高度
        setHeight(height) {
            let that = this;
            if ((!yunj.isString(height) && !yunj.isNumber(height)) || height==""){
                return;
            }
            if (yunj.isPositiveInt(height)) {
                height = height+"px";
            }
            $("#"+that.markdownContainerId).css("height",height)
        }

        // 默认配置
        getCherryOptions() {
            let that = this;
            // 完整配置详见：https://github.com/Tencent/cherry-markdown/wiki/%E9%85%8D%E7%BD%AE%E9%A1%B9%E5%85%A8%E8%A7%A3
            let options = {
                id: that.markdownContainerId,
                nameSpace: 'cherry',
                themeSettings: {
                    // 目前应用的主题
                    mainTheme: 'light',
                    // 目前应用的代码块主题
                    codeBlockTheme: 'default',
                    // 工具栏主题
                    toolbarTheme: 'light',
                },
                editor: {
                    id: that.markdownContainerId + '_code', // textarea 的id属性值
                    name: that.markdownContainerId + '_code', // textarea 的name属性值
                    defaultModel: 'edit&preview',
                }
            };
            if (that.isReadonly()) {
                options.editor.defaultModel = 'previewOnly';
                return options;
            }
            // 工具栏
            options.toolbars = {
                // 选中文字时弹出的“悬浮工具栏”
                bubble: ['bold', 'italic', 'underline', 'strikethrough', 'color', 'size'],
                // 光标出现在行首位置时出现的“提示工具栏”
                float: ['header', 'code'],
            };
            // 判断是否小屏幕（屏宽<=768px）设备：顶部工具栏、顶部右侧工具栏
            if (yunj.isSmallScreen()) {
                options.toolbars.toolbar = that.args.mobileToolbar
            } else {
                options.toolbars.toolbar = that.args.toolbar;
                options.toolbars.toolbarRight = that.args.toolbarRight;
            }
            // 上传文件的时候是否开启多选
            options.multipleFileSelection= {
                video: false,
                audio: false,
                image: true,
                word: false,
                pdf: false,
                file: false,
            };
            // 回调方法
            options.callback = {
                // 文件上传
                fileUpload: function (file, callback) {
                    if (/image/i.test(file.type)) {
                        yunj.fileUpload(file).then(res => {
                            callback(res.data.url);
                        }).catch(err => {
                            yunj.error(err);
                        });
                    } else {
                        yunj.msg('当前仅支持图片上传');
                    }
                },
                // 多文件上传
                fileUploadMulti: function (files, callback) {
                    let promises = [];
                    for (let i = 0; i < files.length; i++) {
                        let file = files[i];
                        if (!(/image/i.test(file.type))) {
                            yunj.msg('当前仅支持图片上传');
                            return;
                        }
                        let promise = new Promise((resolve, reject) => {
                            yunj.fileUpload(file).then(res => {
                                resolve({url: res.data.url, params: {name: res.data.fileName,}});
                            }).catch(err => {
                                reject(err);
                            });
                        });
                        promises.push(promise);
                    }
                    Promise.all(promises).then(res => {
                        callback(res);
                    }).catch(err => {
                        yunj.error(err);
                    });
                }
            };
            return options;
        }

        defineExtraEventBind() {
            let that = this;

        }

    }

    exports('FormFieldMarkdown', FormFieldMarkdown);
});